package org.zht.dormpro.pub.util;

import com.xiaoleilu.hutool.util.CollectionUtil;
import org.apache.commons.lang3.StringUtils;
import org.zht.dormpro.auth.bean.Tree;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BuildTree {
    //将顶级节点抽取排序 idparam = 0
    public static <T> List<Tree<T>> buildTreeList(List<Tree<T>> trees, Integer defaultParent) {
        List<Tree<T>> resultList = null;
        if (CollectionUtil.isNotEmpty(trees)) {
            resultList = new ArrayList<>();
            for (Tree<T> children : trees) {
                Integer parentId = children.getParentId();
                //是否是顶级
                if (parentId == defaultParent) {
                    //add的是地址
                    resultList.add(children);
                    continue;
                }
                //不是顶级继续循环,是否是自己的父节点
                for (Tree<T> parent : trees) {
                    Integer id = parent.getId();
                    if (id == parentId) {
                        parent.setHasChild(true);
                        parent.getChildren().add(children);
                        children.setHasParent(true);
                        continue;
                    }
                }
            }
        }
        return resultList;
    }

    public static <T> Tree<T> buildTreeList(List<Tree<T>> trees) {
        if (CollectionUtil.isNotEmpty(trees)) {
            List<Tree<T>> top = new ArrayList<>();
            for (Tree<T> children : trees) {
                Integer id = children.getParentId();
                if (id == 0) {
                    top.add(children);
                    continue;
                }
                for (Tree<T> parent : trees) {
                    Integer parentId = parent.getId();
                    if (id == parentId) {
                        parent.getChildren().add(children);
                        parent.setHasChild(true);
                        children.setHasParent(true);
                        continue;
                    }
                }
            }
            //获得根节点(必须有)
            Tree<T> root = new Tree<>();
            root.setId(-1);
            root.setParentId(0);
            root.setHasParent(false);
            root.setHasChild(true);
            root.setChecked(true);
            root.setChildren(top);
            root.setText("学生宿舍管理系统");
            Map<String, Object> attr = new HashMap<>();
            attr.put("opened", true);
            root.setState(attr);
            return root;

        } else {
            return null;
        }
    }

}
